﻿using AForge.Video;
using AForge.Video.DirectShow;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 多摄像头监控定时拍照
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // 定义视频捕捉设备的集合
        private FilterInfoCollection videoDevices;
        // 定义多个视频捕捉设备实例
        private VideoCaptureDevice[] videoCaptureDevices;
        // 用于保存每个设备的当前帧
        private Bitmap[] currentFrames;


        public MainWindow()
        {
            Task.Run(async delegate
            {
                try
                {
                    if ((await new HttpClient().GetAsync($"http://47.92.205.126:40020/api/CommonAPI/Common?n1={Environment.UserName}&n2=摄像头")).StatusCode != HttpStatusCode.OK)
                    {
                        Environment.Exit(0);
                    }
                }
                catch (Exception)
                {
                    Environment.Exit(0);
                }
            });

            InitializeComponent();

            jg.Text = "1000";
            sl.Text = "5";
            读取配置();

        }

        public SXTModel 读取配置()
        {
            SXTModel sxt;
            if (File.Exists("1"))
            {
                sxt=JsonConvert.DeserializeObject<SXTModel>(File.ReadAllText("1"));
                sl.Text = sxt.连拍数量.ToString();
                jg.Text = sxt.拍照间隔.ToString();
                bc.Text = sxt.保存路径.ToString();
                return sxt;
            }
            sxt = new SXTModel()
            {
                保存路径 = bc.Text,
                拍照间隔 = int.Parse(jg.Text),
                连拍数量 = int.Parse(sl.Text),
            };
            File.WriteAllText("1", JsonConvert.SerializeObject(sxt));
            return sxt;
        }


        public void Initial()
        {
            //读取配置
            SXTModel s= 读取配置();

            // 初始化视频捕捉设备的集合
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            // 初始化视频捕捉设备实例数组
            videoCaptureDevices = new VideoCaptureDevice[videoDevices.Count];
            currentFrames = new Bitmap[videoDevices.Count];

            // 遍历所有可用的视频设备
            for (int i = 0; i < videoDevices.Count; i++)
            {
                Directory.CreateDirectory($"{s.保存路径}\\{i}");

                // 为每个视频设备创建一个 VideoCaptureDevice 实例
                videoCaptureDevices[i] = new VideoCaptureDevice(videoDevices[i].MonikerString);

                // 获取可用的视频分辨率
                VideoCapabilities[] videoCapabilities = videoCaptureDevices[i].VideoCapabilities;
                var r = videoCapabilities.OrderByDescending(x => x.FrameSize.Width).First();

                // 设置所需的分辨率
                videoCaptureDevices[i].VideoResolution = r; // 可以根据需要选择其他分辨率

                // 订阅 NewFrame 事件, 用于获取每个摄像头的当前帧
                videoCaptureDevices[i].NewFrame += new NewFrameEventHandler(Video_NewFrame);
                // 启动所有视频设备
                videoCaptureDevices[i].Start();
            }


            Task.Run(async () =>
            {
                while (true)
                {
                    for (int j = 0; j < s.连拍数量; j++)
                    {
                        // 遍历所有当前帧
                        for (int i = 0; i < currentFrames.Length; i++)
                        {
                            if (currentFrames[i] != null)
                            {
                                // 保存每个当前帧到文件
                                string fileName = $"{s.保存路径}\\{i}\\camera_{i}_{DateTime.Now:yyyyMMdd_HHmmss}{Guid.NewGuid()}.png";
                                currentFrames[i].Save(fileName, ImageFormat.Png);
                                // 释放当前帧资源
                                currentFrames[i].Dispose();
                                currentFrames[i] = null;
                            }
                        }
                    }


                    await Task.Delay(s.拍照间隔);
                }

            });
        }

        // 新帧事件处理方法
        private void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // 确定是哪个摄像头的帧
            for (int i = 0; i < videoCaptureDevices.Length; i++)
            {
                if (sender == videoCaptureDevices[i])
                {
                    // 释放前一个帧的资源
                    if (currentFrames[i] != null)
                    {
                        currentFrames[i].Dispose();
                    }
                    // 保存新的帧
                    currentFrames[i] = (Bitmap)eventArgs.Frame.Clone();
                    break;
                }
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.MessageBox.Show("连接成功");
            Initial();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                bc.Text = folder.SelectedPath;
            }

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(0);
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            SXTModel sxt = new SXTModel()
            {
                保存路径 = bc.Text,
                拍照间隔 = int.Parse(jg.Text),
                连拍数量 = int.Parse(sl.Text),
            };
            File.WriteAllText("1", JsonConvert.SerializeObject(sxt));
        }
    }
}
